#!/usr/bin/env node
'use strict';

var fs = require('fs'),
  cheerio = require('cheerio'),
  yamlFront = require('yaml-front-matter');

var URL = '{{site.baseurl}}/docs/';

var DIR = __dirname + '/../site/';
var DOCS_LAYOUT = DIR + '_layouts/docs.html';
var COMPILED_DOCS = DIR + '_site/docs';
var TOC = DIR + '_includes/docs_toc.md';

var CONTENT_TAG = '.page-content';
var INNER_LINK_TAG = 'h2';

var writeStream = fs.createWriteStream(TOC, {flags: 'w'}); // w flag means overwrite existing file

writeStream.write('[//]: # (Auto-generated by scripts/generate-toc)\r\n');

// generate markdown for list item
function generateListItem(content, buffer) {
  var indent = '';
  for (var i = 0; i < buffer; i++) {
    indent += '    ';
  }
  return `${indent}- ${content}`;
}

// generate markdown for anchor tag
function generateLink(title, page, local) {
  return `[${title}](${URL}${page}.html${local || ''})`;
}

// parse Docs layout
fs.readFile(DOCS_LAYOUT, function (err, contents) {
  if (err) {
    throw err;
  }

  var front = yamlFront.loadFront(contents.toString());
  var sidebar = front.sidebar; // docs sidebar, top level

  function parseSidebar(sidebar, depth) {
    for (const el of sidebar) {
      // skip break and table of contents itself
      if (!el.break && el.url !== 'toc') {
        var page = `${COMPILED_DOCS}/${el.url}.html`;

        // generate markdown for top level navigation
        var link = generateLink(el.text, el.url);
        var li = generateListItem(link, depth);
        writeStream.write(li + '\r\n');

        // build DOM
        var $ = cheerio.load(fs.readFileSync(page).toString());

        // iterate through links in DOM tree
        $(CONTENT_TAG + ' ' + INNER_LINK_TAG).each(function () {
          // generate markdown for in-page navigation
          var hash = '#' + $(this).attr('id');
          var link = generateLink($(this).text(), el.url, hash);
          var li = generateListItem(link, depth + 1);
          writeStream.write(li + '\r\n');
        });
      }

      // recurse if there is a sub-sidebar
      if (el['sub-sidebar'] !== undefined) {
        parseSidebar(el['sub-sidebar'], depth + 1);
      }
    }
  }

  // begin parse
  parseSidebar(sidebar, 0);
});
